package com.jobs.producer0.main;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

public class CountDownLatchDemo {

    public static int size = 5;

    public static void main(String[] args) {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(size);

        List<Thread> threadList = new ArrayList<>();
        for(int i = 0; i < size; ++i){
            CountDownLatch countDownLatch = new CountDownLatch(1);
            Thread t1 = new Thread(new Athlete(cyclicBarrier, countDownLatch, "起点远动员" + i));
            Thread t2 = new Thread(new Athlete(countDownLatch, "接力运动员"+ i));
            threadList.add(t1);
            threadList.add(t2);
        }

        for(Thread t : threadList){
            t.start();
        }
    }

    static class Athlete implements Runnable{

        private CyclicBarrier cyclicBarrier;

        private  String name;

        CountDownLatch countDownLatch;

        //起跑运动员
        public Athlete(CyclicBarrier cyclicBarrier, CountDownLatch countDownLatch, String name){
            this.countDownLatch = countDownLatch;
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
        }
        //接力远动员
        public Athlete(CountDownLatch countDownLatch, String name){
            this.countDownLatch = countDownLatch;
            this.name = name;
        }

        @Override
        public void run() {
            //判断是否是棋牌
            if(cyclicBarrier  != null){
                System.out.println(name + "就位");
                try {
                    cyclicBarrier.await();
                    System.out.println(name + "到达交接点");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }

            //判断是否是接力
            if(cyclicBarrier == null){
                System.out.println(name + "就位");
                try {
                    countDownLatch.await();
                    System.out.println(name + "到达终点");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

